package com.liangtian.mdm.system.business.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.system.business.model.SysBusiness;
import com.liangtian.mdm.system.business.service.SysBusinessService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.liangtian.mdm.util.RequestUtils;
import com.liangtian.mdm.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 业务类型维护  控制类
 *
 * @author hadoop
 */
@Controller
@RequestMapping("/sysBusCtr")
public class SysBusinessController extends BaseController {

    @Autowired
    SysBusinessService sysBusinessService;

    //Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    /**
     * 查询菜单树
     *
     * @param request
     * @param attribute
     * @return 业务类型
     */
    @ResponseBody
    @RequestMapping(value = "/querySysBusTree", method = RequestMethod.POST)
    public String querySysBusTree(SysBusiness sysBusiness) {
        List<SysBusiness> sysBusLst = new ArrayList<SysBusiness>();
        ResultObject result = new ResultObject();
        try {
            sysBusLst = sysBusinessService.sysBusTree(sysBusiness); //查询菜单树
            result.setData(sysBusLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(sysBusLst);
    }

    /**
     * 查询含有编码属性的业务类型树
     */
    @ResponseBody
    @RequestMapping(value = "/queryCodeSysBusTree", method = RequestMethod.POST)
    public String queryCodeSysBusTree(HttpServletRequest request) {
        List<SysBusiness> sysBusLst = new ArrayList<SysBusiness>();
        ResultObject result = new ResultObject();
        Map<String, Object> param = RequestUtils.paramToMap(request);
        try {
            sysBusLst = sysBusinessService.queryCodeSysBusTree(param);
            result.setData(sysBusLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(sysBusLst);
    }

    /**
     * 查询菜单树
     *
     * @param request
     * @param attribute
     * @return---关联流程
     */
    @ResponseBody
    @RequestMapping(value = "/querySysBusTreeForWk", method = RequestMethod.POST)
    public String querySysBusTreeForWk(SysBusiness sysBusiness) {
        List<SysBusiness> sysBusLst = new ArrayList<SysBusiness>();
        ResultObject result = new ResultObject();
        try {
            sysBusLst = sysBusinessService.sysBusTreeForWk(sysBusiness); //查询菜单树
            result.setData(sysBusLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(sysBusLst);
    }

    //用户维护
    @ResponseBody
    @RequestMapping(value = "/querySysBusTreeForButton", method = RequestMethod.POST)
    public String querySysBusTreeForButton(SysBusiness sysBusiness) {
        List<SysBusiness> sysBusLst = new ArrayList<SysBusiness>();
        ResultObject result = new ResultObject();
        try {
            sysBusLst = sysBusinessService.sysBusTreeForButton(sysBusiness); //查询菜单树
            result.setData(sysBusLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(sysBusLst);
    }

    //
    @ResponseBody
    @RequestMapping(value = "/querySysBusTreeForView", method = RequestMethod.POST)
    public String querySysBusTreeForView(SysBusiness sysBusiness) {
        List<SysBusiness> sysBusLst = new ArrayList<SysBusiness>();
        ResultObject result = new ResultObject();
        try {
            sysBusLst = sysBusinessService.sysBusTreeForView(sysBusiness); //查询菜单树
            result.setData(sysBusLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(sysBusLst);
    }

    /**
     * 左侧列表查询
     *
     * @param menu
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    public JSONObject queryList(SysBusiness sysBusiness) {
        PageInfo pageInfo = sysBusinessService.queryBusByContion(sysBusiness);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * 左侧列表查询
     *
     * @param menu
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryList2", method = RequestMethod.POST)
    public JSONObject queryList2(SysBusiness sysBusiness) {
        PageInfo pageInfo = sysBusinessService.queryBusByContion2(sysBusiness);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * 新增
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertBusiness", method = RequestMethod.POST)
    public JSONObject insertBusiness(HttpServletRequest request, SysBusiness sysBusiness) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            // 获取当前日期
            //Date date = new Date();
            // 获取session中用户
            //获取新增的方向来自哪里
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            sysBusiness.setCreaterId(String.valueOf(user.getUserId()));// 用户创建ID
            sysBusiness.setCreaterName(user.getUserName());// 用户创建名称
            sysBusiness.setIsUsed("0");//通过新增页面新增的，默认的isUsed为“0“
            sysBusinessService.insertBusiness(sysBusiness);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 根据id获取对象信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getBusById", method = RequestMethod.POST)
    public String getBusById(SysBusiness sysBusiness) {
        SysBusiness busOne = null;
        try {
            busOne = sysBusinessService.queryBusById(sysBusiness);
            if (busOne.getpName() == null) {
                busOne.setpName("Tree-Root");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(busOne);
    }

    /**
     * * <p>Title: 删除功能</p>
     * <p>Description: TODO </p>
     * <p>Company:@param request
     * <p>Company:@param ids
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年10月13日下午4:30:22
     */
    @RequestMapping(value = "/deleteBus", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject deleteBus(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<String> idList = new ArrayList<String>();
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;

        String[] list = ids.split(",");
        for (int i = 0; i < list.length; i++) {
            String busId = list[i];
            int count = sysBusinessService.checkBusNode(busId);
            if (count == 0) {//如果它子节点的个数，为0，可以删除，否则，不能删除
                idList.add(busId);
            }
        }
        map.put("idsList", idList);
        int ret = sysBusinessService.deleteBus(map);
        ;
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }

    /**
     * * <p>Title: 校验，新增时，业务类型名称是否存在</p>
     * <p>Description: TODO </p>
     * <p>Company:@param request
     * <p>Company:@param model
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年10月17日下午12:54:58
     */
    @ResponseBody
    @RequestMapping(value = "/checkBusName", method = RequestMethod.POST)
    public JSONObject checkBusName(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsgBusName = new ResponseMsg<String>();
        ResponseMsg<String> rMsgBusTableName = new ResponseMsg<String>();
        try {
            String busName = request.getParameter("busName");
            String busTable = request.getParameter("busTable");

            String dataType = request.getParameter("dataType");
            if (null != dataType)
                dataType = dataType.trim();
            int busCount = sysBusinessService.checkBusName(busName);
            int busTableCount = 0;
            if (!StringUtil.isBlank(busTable))
                busTableCount = sysBusinessService.checkBusTableName(busTable, dataType);
            rMsgBusName.setRspCode(busCount);
            rMsgBusTableName.setRspCode(busTableCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rMsgBusName", rMsgBusName);
        jsonObject.put("rMsgBusTableName", rMsgBusTableName);
        return jsonObject;
    }


    /**
     * * <p>Title: </p>
     * <p>Description: TODO </p>
     * <p>Company:@param request
     * <p>Company:@param sysBusiness
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年10月17日下午4:02:32
     */

    @ResponseBody
    @RequestMapping(value = "/checkBusNameTwo", method = RequestMethod.POST)
    public JSONObject checkBusNameTwo(HttpServletRequest request, SysBusiness sysBusiness) {
        JSONObject jsonObject = new JSONObject();
        int buscount = sysBusinessService.checkBusNameTwo(sysBusiness);
        int busTablecount = 0;
        if (!StringUtil.isBlank(sysBusiness.getBusTable()))
            busTablecount = sysBusinessService.checkBusTableNameTwo(sysBusiness);
        jsonObject.put("buscount", buscount);
        jsonObject.put("busTablecount", busTablecount);
        return jsonObject;
    }

    /**
     * * <p>Title:修改方法 </p>
     * <p>Description: TODO </p>
     * <p>Company:@param model
     * <p>Company:@return </p>
     *
     * @author : xiaoliu
     * @date :2016年10月17日下午4:53:44
     */
    @ResponseBody
    @RequestMapping(value = "/updateBus", method = RequestMethod.POST)
    public JSONObject updateBus(SysBusiness sysBusiness) {
        JSONObject jsonObject = new JSONObject();
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);//获取当前登录人的信息
        sysBusiness.setUpdaterId(String.valueOf(user.getUserId()));// 默认将当前登录人信息userid付给修改人id
        sysBusiness.setUpdaterName(user.getUserName());// 默认将当前登录人信息username付给修改人name
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            sysBusinessService.updateBus(sysBusiness);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rMsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/queryDataTables", method = RequestMethod.POST)
    public ResultObject queryDataTables(HttpServletRequest request) throws IOException {
//    	String param=ReadSystemParam.getValue("EXCLUDEDPATTERN");
        String param = ConstantBean.EXCLUDEDPATTERN;
        List<String> Lst = Arrays.asList(param.split(","));
        List<Map<String, Object>> tableLst = sysBusinessService.queryDataTables(Lst);
        ResultObject result = new ResultObject(tableLst);
        return result;
    }
}
